package com.gilbertoca.igreja.view.dialogs.common;

import com.gilbertoca.igreja.model.Localidad;
import com.gilbertoca.igreja.service.LocalidadService;
import com.gilbertoca.igreja.view.Application;
import com.gilbertoca.igreja.view.component.Buscador;
import com.gilbertoca.igreja.view.component.Listador;
import com.gilbertoca.igreja.view.component.Refreshable;
import com.gilbertoca.igreja.view.dialogs.ConfirmationDialog;
import com.gilbertoca.igreja.view.dialogs.ErrorDialog;
import com.gilbertoca.igreja.view.dialogs.WarningDialog;
import com.gilbertoca.igreja.view.dialogs.common.models.LocalidadTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Timer;
import org.jdesktop.application.Action;

public class LocalidadesDialog extends Listador<Localidad> implements Refreshable {

    private Timer keyTimer;

    private LocalidadService localidadService;

    public LocalidadesDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        localidadService = LocalidadService.get();
        refresh();

        keyTimer = new Timer(1000, new ActionListener (){
             public void actionPerformed(ActionEvent e)
              {
                 buscarBtn.doClick();
                 keyTimer.stop();
              }
        });
    }

     public LocalidadesDialog(java.awt.Frame parent, boolean modal, Buscador buscador, String variable ) {
        super(parent, modal);
        initComponents();
        localidadService = LocalidadService.get();
        this.setBuscando(true);
        this.setBuscador(buscador);
        this.setVariable(variable);
        refresh();
        keyTimer = new Timer(1000, new ActionListener (){
             public void actionPerformed(ActionEvent e)
              {
                 buscarBtn.doClick();
                 keyTimer.stop();
              }
        });
    }

   

    public void refresh() {
        tabla.setModel(new LocalidadTableModel(localidadService.getAll()));
    }

    @Action
    public void nuevo() {
        LocalidadDialog dialog = new LocalidadDialog(Application.getApplication().getMainFrame(), this);
        dialog.setLocationRelativeTo(Application.getApplication().getMainFrame());
        Application.getApplication().show(dialog);
    }
    
    @Action
    public void cerrar() {
        dispose();
    }
    
    @Action
    public void modificar() {
        int row = tabla.getSelectedRow();
       
        if (row >= 0) {
            Localidad r = ((LocalidadTableModel)tabla.getModel()).getElements().get(row);
            LocalidadDialog dialog = new LocalidadDialog(Application.getApplication().getMainFrame(), this,r);
            dialog.setLocationRelativeTo(Application.getApplication().getMainFrame());
            Application.getApplication().show(dialog);
       } else {
            WarningDialog.show("Debe seleccionar una localidad.");
       }     
    }


    @Action
    public void eliminar() {
        int row = tabla.getSelectedRow();

        if (row >= 0) {
            Localidad localidad = ((LocalidadTableModel)tabla.getModel()).getElements().get(row);
            if(localidad != null && ConfirmationDialog.show("¿Desea eliminar la localidad seleccionada?")){
                try{
                    localidadService.remove(localidad);
                    refresh();
                }catch(Exception ex){
                    ErrorDialog.show("No es posible eliminar la localidad.");
                }
           }
       } else {
            WarningDialog.show("Debe seleccionar una localidad.");
       }        
    }

    @Action
    public void limpiar(){
        this.codigo.setText("");
    }

    @Action
    public void buscar() {
        List<Localidad> localidades = localidadService.getLocalidades(codigo.getText());
        tabla.setModel(new LocalidadTableModel(localidades));
    }

    public Localidad select(){
        int row = tabla.getSelectedRow();
        Localidad localidad = null;
        if (row >= 0) 
            localidad = ((LocalidadTableModel)tabla.getModel()).getElements().get(row);

        return localidad;
    }


    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        codigo = new javax.swing.JTextField();
        buscarBtn = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.gilbertoca.igreja.view.Application.class).getContext().getResourceMap(LocalidadesDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Nombre"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setName("tabla"); // NOI18N
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tablaMousePressed(evt);
            }
        });
        tabla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablaKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(resourceMap.getColor("jPanel1.border.highlightColor"), resourceMap.getColor("jPanel1.border.shadowColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.gilbertoca.igreja.view.Application.class).getContext().getActionMap(LocalidadesDialog.class, this);
        jButton1.setAction(actionMap.get("nuevo")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("modificar")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jButton3.setAction(actionMap.get("eliminar")); // NOI18N
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N

        jButton5.setAction(actionMap.get("cerrar")); // NOI18N
        jButton5.setIcon(resourceMap.getIcon("jButton5.icon")); // NOI18N
        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jButton1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton3)
                .add(41, 41, 41)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 112, Short.MAX_VALUE)
                .add(jButton5)
                .addContainerGap())
        );

        jPanel2.setBackground(resourceMap.getColor("jPanel2.background")); // NOI18N
        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(resourceMap.getColor("jPanel2.border.highlightColor"), resourceMap.getColor("jPanel2.border.shadowColor"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        codigo.setText(resourceMap.getString("codigo.text")); // NOI18N
        codigo.setName("codigo"); // NOI18N
        codigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                codigoKeyPressed(evt);
            }
        });

        buscarBtn.setAction(actionMap.get("buscar")); // NOI18N
        buscarBtn.setIcon(resourceMap.getIcon("buscarBtn.icon")); // NOI18N
        buscarBtn.setText(resourceMap.getString("buscarBtn.text")); // NOI18N
        buscarBtn.setName("buscarBtn"); // NOI18N

        jButton6.setAction(actionMap.get("limpiar")); // NOI18N
        jButton6.setIcon(resourceMap.getIcon("jButton6.icon")); // NOI18N
        jButton6.setText(resourceMap.getString("jButton6.text")); // NOI18N
        jButton6.setName("jButton6"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(25, 25, 25)
                        .add(jLabel1)
                        .add(28, 28, 28)
                        .add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 360, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(164, 164, 164)
                        .add(buscarBtn, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(78, 78, 78)))
                .add(335, 335, 335))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(23, 23, 23)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(buscarBtn, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                        .add(2, 2, 2))
                    .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
                        .add(18, 18, 18)
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(15, 15, 15))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void codigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codigoKeyPressed
       if(evt.getKeyCode() == KeyEvent.VK_ENTER){
             //Si presiona el enter, busca y se posiciona en la primer fila de la tabla
             buscarBtn.doClick();
             tabla.requestFocusInWindow();
             evt.setKeyCode(KeyEvent.VK_DOWN);

         }else if(KeyEvent.VK_A <= evt.getKeyCode() && evt.getKeyCode() <= KeyEvent.VK_Z
                 || evt.getKeyCode() == KeyEvent.VK_PERIOD
                 || KeyEvent.VK_0 <= evt.getKeyCode() && evt.getKeyCode() <= KeyEvent.VK_9){
            //Si presiona una tecla valida, busca y se posiciona en la primer fila de la tabla
            keyTimer.start();

         }else if(KeyEvent.VK_LEFT <= evt.getKeyCode() && evt.getKeyCode() <= KeyEvent.VK_DOWN){
             //Si toca las flechas, qiere avegar por la tabla
             tabla.requestFocusInWindow();
             evt.setKeyCode(KeyEvent.VK_DOWN);
         }
    }//GEN-LAST:event_codigoKeyPressed

    private void tablaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyPressed
        // Codigo que maneja las teclas presionadas sobre la tabla

        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            //Si presiona el enter, selecciona el cliente de la tabla
             this.seleccionoDeLista();

        }else if(evt.getKeyCode() == KeyEvent.VK_ESCAPE){
            //Si presiona escape, se reanuda la busqueda desde cero y gana el foco el input
             codigo.setText(null);
             buscarBtn.doClick();
             codigo.requestFocusInWindow();

        }else if(KeyEvent.VK_A <= evt.getKeyCode() && evt.getKeyCode() <= KeyEvent.VK_Z
                 || evt.getKeyCode() == KeyEvent.VK_PERIOD
                 || KeyEvent.VK_0 <= evt.getKeyCode() && evt.getKeyCode() <= KeyEvent.VK_9){
            //Si presiona un caracter valido busca y se posiciona en la primer fila de la tabla
            codigo.setText(codigo.getText()+evt.getKeyChar());
            codigo.requestFocusInWindow();
            keyTimer.start();
         }

    }//GEN-LAST:event_tablaKeyPressed

    private void tablaMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMousePressed
        if(evt.getClickCount() == 2){
            this.seleccionoDeLista();
        }
    }//GEN-LAST:event_tablaMousePressed

    /**
    * @param args the command line arguments
    */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscarBtn;
    private javax.swing.JTextField codigo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable tabla;
    // End of variables declaration//GEN-END:variables
}
